package top.purity.framework.web.sso;

import cn.dev33.satoken.sso.SaSsoProcessor;
import cn.dev33.satoken.sso.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.ObjUtil;
import org.springframework.web.bind.annotation.*;
import top.purity.framework.common.result.GlobalRespCode;

/**
 * @version 1.0
 * @Author Lmh
 * @Description
 * @CreateTime 2023-09-21 20:19
 */

@RestController
public class SsoClientApi {

    @GetMapping("/sso/isLogin")
    public SaResult isLogin() {
        boolean login = StpUtil.isLogin();
        return login ? SaResult.ok() : SaResult.get(GlobalRespCode.UN_LOGIN.getCode(), "", null);
    }

    @GetMapping("/sso/getSsoAuthUrl")
    public SaResult getSsoAuthUrl(@RequestParam("clientLoginUrl") String clientLoginUrl) {
        String serverAuthUrl = SaSsoUtil.buildServerAuthUrl(clientLoginUrl, "");
        return SaResult.data(serverAuthUrl);
    }

    /**
     * 根据ticket进行登录
     * @param ticket 票据
     * @return token
     */
    @PostMapping("/sso/doLoginByTicket")
    public SaResult doLoginByTicket(@RequestParam("ticket") String ticket) {
        Object loginId = SaSsoProcessor.instance.checkTicket(ticket, "/sso/doLoginByTicket");
        if(ObjUtil.isNotEmpty(loginId)) {
            StpUtil.login(loginId);
            return SaResult.data(StpUtil.getTokenValue());
        }
        return SaResult.error("无效ticket：" + ticket);
    }

}
